import axios from 'axios'
//引入仓库
import store from '@/store'
//引入路由
import router from '@/router'
//引入element组件
import { Message } from 'element-ui'

const request = axios.create({
  baseURL:process.env.VUE_APP_BASE_API,
  timeout:15000
})
request.interceptors.request.use(config=>{
  if(store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }

  return config
},(error)=>{
  return new Promise.reject(new Error(error))
})


request.interceptors.response.use((response)=>{
  if (response.data instanceof Blob) return response.data
  const {success,message,data} = response.data
  if(success) {
    return data
  }else {
    Message({
      type:'error',
      message
    })
    return new Promise.reject(new Error(message))
  }
},async (error)=>{
  // 判断token是否失效
  if(error.response.status === 401) {
    Message({
      type:'error',
      message:'登录失效，请重新登录'
    })
    await store.dispatch('loguot')
    //路由跳转
    router.push('/login')
    return Promise.reject(new Error('登录失效，请重新登录'))
  }
  Message({
    type:'error',
    message:error.message
  })
  return  Promise.reject(error.message)
})
export default request